package com.desay.pangoo.itmt.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.desay.pangoo.common.lite.lang.web.BusinessException;
import com.desay.pangoo.common.lite.lang.web.PangooWebConstant;
import com.desay.pangoo.common.lite.spring.web.ControllerCommonUtils;
import com.desay.pangoo.itmt.entity.WorkGroupEntity;
import com.desay.pangoo.itmt.enums.ExceptionCodeEnum;
import com.desay.pangoo.itmt.repository.WorkGroupRepository;
import com.desay.pangoo.itmt.repository.spec.ExpandCriteria;
import com.desay.pangoo.itmt.repository.spec.Restrictions;
import com.desay.pangoo.itmt.service.WorkGroupService;

import cn.hutool.core.collection.CollUtil;

/**
 * @author uidq1163
 */
@Service
public class WorkGroupServiceImpl implements WorkGroupService {

	@Autowired
	WorkGroupRepository workGroupRepository;

	@Override
	public Long create(String groupName, String ptnHeader) {
		String user = ControllerCommonUtils.getHeader(PangooWebConstant.HEADER_NAME_USER_FULL_NAME);
		WorkGroupEntity workGroupEntity = new WorkGroupEntity();
		if (null != workGroupRepository.findByWorkGroupName(groupName)) {
			throw new BusinessException(ExceptionCodeEnum.WORK_GROUP_EXIST);
		}
		if (null != workGroupRepository.findByPtnHeader(ptnHeader)) {
			throw new BusinessException(ExceptionCodeEnum.WORK_GROUP_EXIST);
		}
		workGroupEntity.setWorkGroupName(groupName);
		workGroupEntity.setPtnHeader(ptnHeader);
		workGroupEntity.setCreator(user);
		workGroupEntity = workGroupRepository.save(workGroupEntity);
		return workGroupEntity.getId();
	}

	@Override
	public void delete(Long id) {
		workGroupRepository.deleteById(id);
	}

	@Override
	public void update(Long id, String groupName) {
		String user = ControllerCommonUtils.getHeader(PangooWebConstant.HEADER_NAME_USER_FULL_NAME);
		ExpandCriteria<WorkGroupEntity> c = new ExpandCriteria<>();
		c.add(Restrictions.ne("id", id, false));
		c.add(Restrictions.eq("workGroupName", groupName, false));
		List<WorkGroupEntity> exists = workGroupRepository.findAll(c);
		if (CollUtil.isNotEmpty(exists)) {
			throw new BusinessException(ExceptionCodeEnum.WORK_GROUP_EXIST);
		}
		Optional<WorkGroupEntity> option = workGroupRepository.findById(id);
		if (option.isPresent()) {
			WorkGroupEntity workGroupExist = option.get();
			workGroupExist.setWorkGroupName(groupName);
			workGroupExist.setUpdator(user);
			workGroupRepository.save(workGroupExist);
		} else {
			throw new BusinessException(ExceptionCodeEnum.WORK_GROUP_NOT_EXIST);
		}
	}

	@Override
	public List<WorkGroupEntity> getAll() {
		ExpandCriteria<WorkGroupEntity> c = new ExpandCriteria<>();
		return workGroupRepository.findAll(c, Sort.by(Sort.Direction.ASC, "indexNo"));
	}
}
